package com.sparsearr.datastructures.ztr.sort;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/5/27 21:35
 * @Description: 快速排序
 * @Version: 1.0
 */

public class QuickSort {
    private static final Logger logger = LogManager.getLogger(QuickSort.class);

    public static void main(String[] args) {
//        int[] arr = {-9, 78, 0, 23, -567, 70};
        int[] arr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int) (Math.random() * 8000000);
        }

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(date);
        System.out.println("排序钱的时间是：" + dateStr);

        quickSort(arr, 0, arr.length - 1);
//        System.out.println("排序后" + Arrays.toString(arr));

        Date date1 = new Date();
        String dateStr1 = simpleDateFormat.format(date1);
        System.out.println("排序钱的时间是：" + dateStr1);
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left >= right) return;

        int l = left;
        int r = right;
        int mid = left + (right - left) / 2;
        // 正确选择中间值作为 pivot
        int pivot = arr[mid];

        while (l < r) {
            // 找到 >= pivot 的位置
            while (arr[l] < pivot) l++;
            // 找到 <= pivot 的位置
            while (arr[r] > pivot) r--;

            if (l < r) {
                // 交换
                int temp = arr[l];
                arr[l] = arr[r];
                arr[r] = temp;

                if (arr[l] == pivot) r--;
                if (arr[r] == pivot) l++;
            }
        }

        // 防止死循环
        if (l == r) {
            l++;
            r--;
        }

        // 对左边子数组排序
        quickSort(arr, left, r);
        // 对右边子数组排序
        quickSort(arr, l, right);
    }
}
